<?php
/**
 * Openid.php
 *
 * @category    Madoqua
 * @package     Validate
 * @subpackage  Login
 */

/** base class */
require_once 'Zend/Validate/Abstract.php';

/**
 * Madoqua_Validate_Openid
 *
 * @category    Madoqua
 * @package     Validate
 * @subpackage  Login
 */
class Madoqua_Validate_Openid extends Zend_Validate_Abstract
{
    /**
     * database connection
     *
     * @var Zend_Db_Adapter_Abstract
     */
    protected $_db;
    
    /**
     * no user
     */
    const USER = 1;

    /**
     * openid problem
     */
    const OPENID = 2;

    /**
     * Validation failure message template definitions
     *
     * @var array
     */
    protected $_messageTemplates = array(
        self::USER    => "'%value%' does not have a matching user",
        self::OPENID => "'%value%' does not produce a valid openid result"
    );    

    /**
     * auth instance
     *
     * @var Zend_Auth
     */
    private $_auth;
    
    /**
     * openid auth adapter
     *
     * @var Zend_Auth_Adapter_OpenId
     */
    private $_openIdAdapter;    

    /**
     * constructor
     *
     * @param Zend_Auth $auth
     * @param Zend_Auth_Adapter_OpenId $adapter
     * 
     */
    public function __construct($auth, $adapter)
    {
        $this->_db = Madoqua_Application::getDatabase();
        //get the db connection
        
        $this->_auth = $auth;
        $this->_openIdAdapter = $adapter;
        //auth/adapter
    }

    /**
     * validate login
     *
     * @param string $value
     */
    public function isValid($value)
    {
        $value = rtrim($value, '/');
        $this->_setValue($value);
        //the value
        
        $select = $this->_db->select()
        ->from('user', array('id'))
        ->where('openid = ?', $value);

        $user = $this->_db->fetchOne($select);

        if ($user === false) {
            $this->_error(self::USER);
            return false;
        } else {
            $this->_openIdAdapter->setIdentity($value);
            $result = $this->_auth->authenticate($this->_openIdAdapter);
            return $result->isValid();            
        }

        return true;

    }
}